package com.rzico.sbl.ui.order

import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderCancelBinding
import com.rzico.sbl.model.OrderBarrelData
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.glideExt.loadRoundedImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import net.mikaelzero.mojito.ext.mojito
import net.mikaelzero.mojito.impl.DefaultPercentProgress
import net.mikaelzero.mojito.impl.NumIndicator
import net.mikaelzero.mojito.interfaces.IProgress
import net.mikaelzero.mojito.loader.InstanceLoader
import org.json.JSONArray
import org.json.JSONObject

class OrderCancelActivity : BaseActivity(R.layout.activity_order_cancel) {

    private val mBinding by lazy { ActivityOrderCancelBinding.bind(getRootView()) }

    private var mShopId = ""
    private var mOrderSn = ""
    private var mAdminId = ""
    private var mAdminName = ""
    private var mOrderMethod = ""
    private var mReceivePhone = ""
    private var mHopeDate = ""     //预约时间
    private var mEstimateDate = "" //预计送达

    // 图片列表
    private var mPhotoList = ArrayList<String>()

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        initTitle(title = "商品核销")

        initLayout()
        initPhotoLayout()

        getData()
    }

    private fun initLayout() {
        mBinding
            .cancelList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(
                    SpaceTBDecoration(
                        top = 5f,
                        hasHeader = false,
                        hasFooter = false,
                        spaceColor = R.color.white
                    )
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderGoods>(R.layout.item_order_detail_list) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                            text(R.id.item_order_price, "")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            visibility(
                                R.id.item_order_img_label,
                                visibleValue { bean.first }
                            )

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_order_img_type) {
                                when (mOrderMethod) {
                                    "offline" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order03)
                                    }

                                    "eleme", "elemengc" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order04)
                                    }

                                    "meituan" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order05)
                                    }

                                    "nongfu" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order06)
                                    }

                                    "jd" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order10)
                                    }

                                    "taobao" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order11)
                                    }

                                    "pinduoduo" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order12)
                                    }

                                    "dummy" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order22)
                                    }

                                    "ali" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order26)
                                    }

                                    else -> it.gone()
                                }
                            }

                            with<ImageView>(R.id.item_order_img_status) {
                                it.isVisible = mHopeDate.isNotEmpty()

                                mHopeDate.notEmpty {
                                    if (longValue < mEstimateDate.longValue)
                                        it.setImageResource(R.mipmap.icon_order07)
                                    else
                                        it.setImageResource(R.mipmap.icon_order02)
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }
    }

    private fun initPhotoLayout() {
        mBinding.apply {
            cancelPhoto.also { layout ->
                layout.isNestedScrollingEnabled = false
                layout.layoutManager = FullyGridLayoutManager(baseContext, 3)
                layout.adapter = SlimAdapter.creator()
                    .register<String>(R.layout.item_photo_grid) { jector, bean, index ->
                        jector.apply {
                            gone(R.id.item_photo_del)

                            with<ImageView>(R.id.item_photo_img) {
                                it.loadRoundedImage(
                                    url = bean,
                                    radius = 10f
                                )
                            }

                            clicked {
                                layout.mojito(R.id.item_photo_img) {
                                    urls(mPhotoList)
                                    position(index, headerSize = 1, footerSize = 1)
                                    autoLoadTarget(false)
                                    setProgressLoader(object : InstanceLoader<IProgress> {
                                        override fun providerInstance(): IProgress {
                                            return DefaultPercentProgress()
                                        }
                                    })
                                    progressLoader { DefaultPercentProgress() }
                                    setIndicator(NumIndicator())
                                }
                            }
                        }
                    }
                    .attachTo(layout)
            }

            (cancelPhoto.adapter as SlimAdapter).setDataList(mPhotoList)
        }
    }

    override fun initListener() {
        mBinding.apply {
            cancelCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            cancelNumCopy.oneClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            btCancel.oneClick {
                getViewModel()
                    .offOrder(
                        intent.getExtra("shippingSn"),
                        cancelMemo.textTrim
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("核销成功！")

                            intent
                                .getIntExtra("index", -1)
                                .also {
                                    if (it > -1) {
                                        // 更新订单列表
                                        LiveEventBus
                                            .get("orderList")
                                            .post("refresh")
                                    }
                                }

                            // 更新订单详情
                            LiveEventBus
                                .get("orderDetail")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    /**
     * 核销详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .offDetail(intent.getExtra("orderSn"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mShopId = obj.optNotNull("shopId")
                    mOrderSn = obj.optNotNull("orderSn")
                    mAdminId = obj.optNotNull("adminId")
                    mAdminName = obj.optNotNull("adminName")
                    mOrderMethod = obj.optNotNull("orderMethod")
                    mHopeDate = obj.optNotNull("hopeDate")

                    val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                    mReceivePhone = objReceive.optNotNull("phone")

                    mBinding.apply {
                        cancelAmount.text = obj.optNotNull("amount").formatDecimal()

                        // 应收金额
                        cancelShou.text = obj.optNotNull("amountPayable").formatDecimal()
                        // 上期欠款
                        cancelShou1.text = obj.optNotNull("arrears").formatDecimal()
                        // 应收水票
                        cancelShui.text = obj.optNotNull("paperPayable")
                        // 上期欠票
                        cancelShui1.text = obj.optNotNull("ticket")
                        // 运费
                        cancelFee.text = obj.optNotNull("freight").formatDecimal()
                        // 空桶押金
                        cancelYa.text = obj.optNotNull("pledgePayable").formatDecimal()
                        // 所在楼层
                        cancelCeng.text =
                            when (val floor = objReceive.optNotNull("level")) {
                                "0" -> "有电梯"
                                else -> "${floor}楼"
                            }
                        // 结算货款
                        cancelJie.text = obj.optNotNull("cost").formatDecimal()
                        // 配送费用
                        cancelPei.text = obj.optNotNull("shippingFreight").formatDecimal()
                        // 送货工资
                        cancelSong.text = obj.optNotNull("adminFreight").formatDecimal()
                        // 楼层费
                        cancelSong1.text = obj.optNotNull("levelFreight").formatDecimal()

                        /*---------------------- 客户信息 ----------------------*/
                        // 姓名电话
                        cancelName.text = "${objReceive.optNotNull("consignee")}  ${
                            when {
                                userRole in "1,2"
                                        || privacyStatus == "off" -> mReceivePhone

                                else -> mReceivePhone.phoneReplaceWithStar()
                            }
                        }"
                        // 是否拨打电话
                        cancelCall.isVisible = userRole in "1,2"
                        // 收货地址
                        cancelAdress.text = objReceive.optNotNull("address")
                        // 买家留言
                        cancelMai.text =
                            obj.optNotNull("orderMemo")
                                .notEmpty { cancelMaiLl.visible() }
                        // 商家备注
                        cancelCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { cancelCmemoLl.visible() }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单状态
                        cancelStatus.text = obj.optNotNull("statusDescr")
                        // 订单编号
                        cancelNum.text = mOrderSn
                        // 订单类型
                        cancelType.text =
                            obj.optNotNull("orderMethod")
                                .run {
                                    mOrderMethod = this
                                    notEmpty { cancelTypeLl.visible() }

                                    when (this) {
                                        "online" ->
                                            when (obj.optNotNull("paymentPluginId")) {
                                                "ticketPayPlugin" -> "货到付款"
                                                else -> "线上订单"
                                            }

                                        "ali" ->
                                            when (obj.optNotNull("paymentPluginId")) {
                                                "ticketPayPlugin" -> "货到付款"
                                                else -> "支付宝"
                                            }

                                        "offline" -> "人工报单"
                                        "history" -> "人工补单"
                                        "nongfu" -> "农夫APP"
                                        "meituan" -> "美团"
                                        "eleme", "elemengc" -> "饿了么"
                                        "jd" -> "京东"
                                        "taobao" -> "淘宝"
                                        "pinduoduo" -> "拼多多"
                                        else -> "其他"
                                    }
                                }
                        // 支付方式
                        cancelPay.text =
                            obj.optNotNull("payMethodName")
                                .also {
                                    cancelPayLl.isGone = it.isEmpty()
                                }
                        // 电子签单
                        obj.optNotNull("signature")
                            .notEmpty {
                                cancelSignLl.visible()

                                Glide.with(getIContext())
                                    .load(this)
                                    .into(cancelSign)
                            }
                        // 下单时间
                        cancelCreate.text = obj.optNotNull("createDate").getTimeString()
                        // 预计送达
                        cancelYue.text =
                            obj.optNotNull("estimateDate")
                                .also { mEstimateDate = it }
                                .notEmpty { cancelYueLl.visible() }
                                .getTimeString()
                        // 送达时间
                        cancelDa.text =
                            obj.optNotNull("deliveryDate")
                                .notEmpty { cancelDaLl.visible() }
                                .getTimeString()
                        // 派单留言
                        cancelPai.text =
                            obj.optNotNull("memo")
                                .trimEnd('\n')
                                .notEmpty { cancelPaiLl.visible() }
                        // 配送方式
                        cancelDeliver.text =
                            obj.optNotNull("shippingMethod")
                                .notEmpty { cancelDeliverLl.visible() }
                        // 配送站点
                        cancelZhan.text =
                            obj.optNotNull("shopName")
                                .notEmpty { cancelZhanLl.visible() }
                        // 配送人员
                        cancelRen.text =
                            obj.optNotNull("adminName")
                                .notEmpty { cancelRenLl.visible() }

                        /*---------------------- 回桶明细 ----------------------*/
                        val objBarrel = obj.optJSONArray("shippingBarrels") ?: JSONArray()
                        val barrelList = arrayListOf<OrderBarrelData>()
                        barrelList.addItems(
                            JsonUtil.toList(
                                objBarrel.toString(),
                                OrderBarrelData::class.java
                            )
                        )
                        cancelDispatch.text =
                            barrelList
                                .also {
                                    if (it.isNotEmpty()) cancelDispatchLl.visible()
                                }
                                .joinToString("\n") {
                                    "${it.name} | 送出${it.quantity}桶 | 收回${it.returnQuantity}桶"
                                }
                    }

                    /*---------------------- 商品信息 ----------------------*/
                    val objOrder = obj.optJSONArray("shippingItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )

                    // 是否首单
                    val isFirst = obj.optBoolean("isFirst")
                    mList.forEach { (it as OrderGoods).first = isFirst }

                    mAdapter.setDataList(mList)

                    /*---------------------- 拍照记录 ----------------------*/
                    val objPhoto = obj.optJSONArray("shippingPhotos") ?: JSONArray()
                    mPhotoList.clear()
                    mPhotoList.addItems(
                        JsonUtil.toList(
                            objPhoto.toString(),
                            String::class.java
                        )
                    )
                    if (mPhotoList.isNotEmpty()) {
                        mBinding.cancelPhotoLl.visible()
                        (mBinding.cancelPhoto.adapter as SlimAdapter).notifyDataSetChanged()
                    }

                    // 商品总数
                    mBinding.cancelTotal.text = kotlin.run {
                        var total = 0
                        mList.forEach {
                            it as OrderGoods
                            total += it.quantity.intValue
                        }
                        total.toString()
                    }
                }
            )
    }

}